<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="users" width="100%" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 状态插槽，slot-scope="scope"接收当前作用域的数据，scope.row拿到当前行的数据 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChangged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 状态插槽，slot-scope="scope"接收当前作用域的数据，scope.row拿到当前行的数据 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="用户设置" placement="top">
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="setUserRole(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-button type="danger" icon="el-icon-delete" circle @click="removeUser(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalpage"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="showAddVisible" width="50%" @close="addFormClosed">
      <el-form
        ref="addUserFormRefs"
        :model="addUserForm"
        label-width="80px"
        :rules="addUserFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="个人邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="showEditVisible" width="50%" @close="editFormClosed">
      <el-form
        ref="editUserFormRefs"
        :model="editUserForm"
        label-width="80px"
        :rules="editUserFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="个人邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="showAllotVisible" @close = 'setUserRoleClosed'>
      <el-form>
        <p>当前用户: {{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <el-form-item label="分配新角色">
          <el-select v-model="selectRoleId" placeholder="请选择用户角色">
            <el-option
              :label="item.roleName"
              :value="item.id"
              v-for="item in rolesList "
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAllotVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!regMobile.test(value)) {
        return callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    }
    return {
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      users: [],
      totalpage: 1,
      //   控制添加用户对话框的显示与隐藏
      showAddVisible: false,
      // 控制修改用户对话框的显示与隐藏
      showEditVisible: false,
      // 添加用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 查询到的用户信息对象
      editUserForm: {},
      // 分配角色对话框的显示隐藏
      showAllotVisible: false,
      // 分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      //  被选择的角色id
      selectRoleId: '',
      // 添加用户表单的验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请设置用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          //   注意validator传入的不需要加''
          {
            validator: checkMobile,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      },
      editUserFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          //   注意validator传入的不需要加''
          {
            validator: checkMobile,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表的方法
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.$message.success(res.meta.msg)
      this.totalpage = res.data.total
      this.pagenum = res.data.pagenum
      this.users = res.data.users
    },
    // 监听pageSize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听pagenum改变的的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChangged(userInfo) {
      // 使用模板字符串``
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('设置用户状态失败')
      }
      this.$message.success(res.meta.msg)
    },
    // 监听添加用户对话框的关闭事件
    addFormClosed() {
      // 实现添加表单的重置从操作
      this.$refs.addUserFormRefs.resetFields()
    },
    // 点击按钮，添加用户
    addUser() {
      // 进行提交前的预验证
      this.$refs.addUserFormRefs.validate(async v => {
        if (!v) return
        // 可以调用api发起添加用户请求
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 隐藏添加用户的对话框
        this.showAddVisible = false
        // 重新获取添加用户列表数据
        this.getUserList()
      })
    },
    // 根据id发起请求并展示编辑用户对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.editUserForm = res.data
      this.showEditVisible = true
    },
    editFormClosed() {
      // 实现添加表单的重置从操作
      this.$refs.editUserFormRefs.resetFields()
    },
    editUser() {
      // 完成提交修改表单前的预验证
      this.$refs.editUserFormRefs.validate(async v => {
        if (!v) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUserForm.id,
          { email: this.editUserForm.email, mobile: this.editUserForm.mobile }
        )
        if (res.meta.status !== 200) {
          return this.$$message.error('更新用户信息失败！')
        }
        // 关闭对话框
        this.showEditVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功*
        this.$message.success(res.meta.msg)
      })
    },
    // 根据id删除对应的用户信息
    async removeUser(id) {
      // 弹框询问是否删除数据
      // 如果确认删除，则返回字符串‘confirm’
      // 如果取消删除，则返回字符串‘cancel’
      const confirmRes = await this.$confirm(
        '此操作将删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 确认删除后发起请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      // 删除成功后刷新数据列表
      this.getUserList()
    },
    // 显示用户设置的对话框
    async setUserRole(userInfo) {
      this.userInfo = userInfo
      this.showAllotVisible = true
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    // 点击按钮发起请求保存新角色
    async saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择需要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) {
        return this.$message(res.meta.msg)
      }
      this.$message(res.meta.msg)
      this.getUserList()
      this.showAllotVisible = false
    },
    // 监听设置用户角色的窗口状态
    setUserRoleClosed () {
      this.selectRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped>
</style>
